<?php

namespace App\Models;

use App\Http\Controllers\Easemob;
use App\Util\Tool;
use App\Util\Url;
use Carbon\Carbon;
use Illuminate\Database\Eloquent\Model;

use  Illuminate\Support\Facades\DB;

class Doctor extends Model
{
    protected $table = 'c_doctors';

    /**
     * @param $pictures
     * @return void
     * 多图片添加使用
     */
    public function setCertificateAttribute($pictures)
    {
        if (is_array($pictures)) {
            $this->attributes['certificate'] = json_encode($pictures);
        }
    }

    /**
     * @param $pictures
     * @return mixed
     * 多图片读取使用
     */
    public function getCertificateAttribute($pictures)
    {
        return json_decode($pictures, true);
    }

    /**
     * @return \Illuminate\Database\Eloquent\Relations\HasMany
     * 科室评价
     */
    public function evaluate()
    {
        return $this->hasMany('App\Models\Evaluate', 'goods_id');
    }

    /**
     * @return \Illuminate\Database\Eloquent\Relations\HasMany
     * 获取用户关注
     */
    public function follows()
    {
        return $this->hasMany('App\Models\Follow','work_id','work_id');
    }

    /**
     * @return \Illuminate\Database\Eloquent\Relations\HasOne
     *
     * 所属科室分类
     */
    public function clinic()
    {
        return $this->hasOne('App\Models\ClinicCategory', 'id', 'clinic_id');
    }

    /**
     * 所属职称
     * @return \Illuminate\Database\Eloquent\Relations\HasOne
     */
    public function professional()
    {
        return $this->hasOne('App\Models\Professional', 'id', 'professional_id');
    }

    /***
     * @return \Illuminate\Database\Eloquent\Relations\BelongsTo
     *所属医护室
     */
    public function works()
    {
        return $this->belongsTo('App\Models\DoctorWorks', 'work_id');
    }

    /**
     * 
     * 获取子分类
     */
    public function getClinicId($clinid)
    {
        return (new ClinicCategory())->where([['pid','=',$clinid]])->pluck("id");
    }
    
    /****
     * @param $param
     * @return mixed
     * 医护列表
     */
    public function getDoctorList($param)
    {
        $field = "online";
        $asc = "desc";
        $where[] = ["state","=",1];
        $or_where = [];
        $in = [];
        if (isset($param['answer_num']) && !empty($param['answer_num'])) {  //回复数
            if ($param['answer_num'] == 1) {//倒序
                $field = "consult_num";
                $asc = "desc";
            } else {
                $field = "consult_num";
                $asc = "asc";
            }
        }
        if (isset($param['good_evaluat']) && !empty($param['good_evaluat'])) {  //好评
            if ($param['good_evaluat'] == 1) {//倒序
                $field = "good_evaluat";
                $asc = "desc";
            } else {
                $field = "good_evaluat";
                $asc = "asc";
            }
        }
        if (isset($param['price']) && !empty($param['price'])) {  //价格
            if ($param['price'] == 1) {//倒序
                $field = "imagetext_price";
                $asc = "desc";
            } else {
                $field = "imagetext_price";
                $asc = "asc";
            }
        }

        if (isset($param['service_type']) && !empty($param['service_type'])) { //服务类型
//            $where[] = [function( $query )use( $param ){
//                $tmp_where = [];
//                if($param['service_type'] ==1){
//                    $params_arr = [1,3];
//                }elseif ($param['service_type'] ==2){
//                    $params_arr = [2,3];
//                }
//                foreach ($params_arr as $key=>$value) {
//                    $tmp_where[] = ['service_type', 'LIKE', '%'.$value.'%', 'OR'];
//                }
//                 return $query->where($tmp_where);
//            }];
            if ($param['service_type'] == 1) {
                $params_arr = [1, 3];
            } elseif ($param['service_type'] == 2) {
                $params_arr = [2, 3];
            }
            $where[] = [function ($query) use ($params_arr) {
                $query->whereIn('service_type', $params_arr);
            }];
        }

        if (isset($param['clinic_id']) && !empty($param['clinic_id'])) {  //科室id
            $ids = $this->getClinicId($param['clinic_id'])->toArray();
            array_push($ids, $param['clinic_id']);
            $where[] = [function ($query) use ($ids) {
                $query->whereIn('clinic_id', $ids);
            }];
//            $where[] = ['clinic_id', '=', $param['clinic_id']];
        }
        if (isset($param['professional_id']) && !empty($param['professional_id'])) {  //职称
            $where[] = ['professional_id', '=', $param['professional_id']];
        }
        if (isset($param['title']) && !empty($param['title'])) {  //标题
            $or_where[] = ['hospital', 'like', '%' . $param['title'] . '%', 'OR'];
            $or_where[] = ['real_name', 'like', '%' . $param['title'] . '%', 'OR'];
            $ids = $this->getCategoryId($param['title']);
//            $in[] = [function ($query) use ($ids) {
//                $query->whereIn('clinic_id', $ids);
//            }];
        }
//        $result = $this->where($where)->with(['professional', 'clinic'])->orWhere($orwhere)->orderBy($field, $asc)->paginate(15);
        $result = $this->where($where)->with(['professional', 'clinic'])->where($or_where)->orderBy($field, $asc)->paginate(15);
        if (!empty($result)) {
            $result = $result->toArray();
            $host = (new Url());
            foreach ($result['data'] as $k => $v) {
                $result['data'][$k]['profile'] = $host::getHttpHost() . 'upload/' . $v['profile'];
                $result['data'][$k]['front_card'] = $host::getHttpHost() . 'upload/' . $v['front_card'];
                $result['data'][$k]['behind_card'] = $host::getHttpHost() . 'upload/' . $v['behind_card'];

            }
            return $result;
        }
        return $result;
    }

    public static function setDoctorOnline($data,$param)
    {
        //判断医师是否在线
        $ts['type'] = 2;
        $ts['user_id'] = $data['id'];
        $tool_name = Tool::getUserNameForIm($ts);
        $logins_status = (new Easemob())->isOnline($tool_name['username']);
        if (isset($logins_status['data']) && $logins_status['data'][$tool_name['username']] == "online") {
            self::where([['id', '=', $data['id']]])->update(["online" => 1]);
        } else {
            self::where([['id', '=', $data['id']]])->update(["online" => 0]);
        }
        Tool::SetDoctorAndUpToken($data['api_token'],$data['account']);
        return true;
    }


    /***
     * @param $data
     * @return mixed
     * 获取医师信息
     */
    public static function getInfo($data)
    {
        return self::where("id", '=', $data['id'])->first();
    }

    /***
     * @param $data
     * @return mixed
     * 获取医师信息通过id
     */
    public static function getInfoById($id)
    {
        return self::where("id", '=', $id)->first();
    }

    /****
     * @param $title
     * @return mixed
     * 或者分类ID
     */
    public function getCategoryId($title)
    {
        return (new ClinicCategory())->where([['classify_name', 'like', '%' . $title . '%']])->pluck("id");
    }

    /****
     * @param $doctor_id
     * 医师id
     */
    public function getDoctorInfo($param, $offset = 1, $limit = 10)
    {
        $host = (new Url());
        $result = $this->where("id", '=', $param['doc_id'])->with(['clinic', 'professional', 'evaluate' => function ($query) use ($offset, $limit,$param) {
            $query->orderBy('created_at', 'desc')->with(["user"])->where([['types', '=', 3],['goods_id','=',$param['doc_id']]])->limit($limit);
        }])->first();
        if(empty($result)){
            return [];
        }
        $result->total_valuate = (new Evaluate())->where([['types', '=', 3], ['goods_id', '=', $param['doc_id']]])->count();
        $result->nohost_profile =  $result->profile;
        $result->nohost_front_card =  $result->front_card;
        $result->nohost_behind_card =  $result->behind_card;
        $result->nohost_certificate =  $result->certificate;
        $result->profile = $host::getHttpHost() . 'upload/' . $result->profile;
        $result->front_card = $host::getHttpHost() . 'upload/' . $result->front_card;
        $result->behind_card = $host::getHttpHost() . 'upload/' . $result->behind_card;
        if($result->certificate){
            $uri = [];
            foreach($result->certificate as $kk=> $vv){
                $uri[] = $host::getHttpHost() . 'upload/' .$vv;
            }
            $result->certificate  = $uri;
        }
        $result->is_follow = 0;
        $result->is_mydoctor = 0;
        if (isset($param['user_id'])) {
            $is = (new Follow())->where([['work_id', '=', $param['doc_id']], ['user_id', '=', $param['user_id']], ['type', '=', 1]])->first();
            if ($is) {
                $result->is_follow = 1;
            }
            $ismy = (new Mydoctor())->where([['doctor_id', '=', $param['doc_id']], ['user_id', '=', $param['user_id']]])->first();
            if ($ismy) {
                $result->is_mydoctor = 1;
            }
        }
        if (!empty($result)) {
            $res = $result->toArray();
            //pand医师是否排班
            $today_time = $todayStart = Carbon::today();
            $lit = (new PlanTime())->where("dates",">",$today_time)->where([['doctor_id', '=', $param['doc_id']]])->first();
            $res['is_schedul'] = 0;
            if ($lit) {
                $res['is_schedul'] = 1;
            } else {
                $t_lit = (new PlanTime())->where("dates", "=", $today_time)->where("times", ">", date("H:i:s", time()))->where([['doctor_id', '=', $param['doc_id']]])->first();
                if ($t_lit) {
                    $res['is_schedul'] = 1;
                }
            }
            $res['all_evaluate'] = (new Evaluate())->where([['goods_id', '=', $param['doc_id']], ['types', '=', 3]])->count("id");
            if (!empty($res['evaluate'])) {
                $tool = new Tool();
                $host = new Url();
                foreach ($res['evaluate'] as $k => &$v) {
                    $v['images'] = $tool->addHostToImage($v['images']);
                    $v['videos'] = $host::getHttpHost() . 'upload/' . ($v['videos']);
                    if ($v['user']) {
                        $v['user']['image'] = $host::getHttpHost() . 'upload/' . $v['user']['image'];
                    }
                    $v['evaluate_instime'] = Tool::time2Units(strtotime($v['created_at']));
                }
            }
            return $res;
        }
        return [];
    }

    /***
     * 增加咨询数
     */
    public function addConsult($data)
    {
        return $this->where([['id', '=', $data['doctor_id']]])->increment('consult_num');
    }

    /**
     * 获取下拉列表
     * @return array
     */
    public function getOptions()
    {
        $options = $this->select('id', 'real_name as text')->get();
        $selectOption = [];
        foreach ($options as $option) {
            $selectOption[$option->id] = $option->text;
        }
        return $selectOption;
    }

    /***
     * 医护端医生列表
     *
     */
    public function getWorkDoctorList($filter)
    {
        if(isset($filter['type']) && $filter['type'] == 1){
            $res =  $this->with(['professional','clinic'])->where([['work_id', '=', $filter['work_id']]])->get();
        }else{
            $res =  $this->with(['professional','clinic'])->where([['work_id', '=', $filter['work_id']],['state','=',1]])->get();
        }
        $host = Url::getHttpHost();
        foreach($res as $k=>&$v){
            $v->profile = !empty( $v->profile)?$host.'upload/'. $v->profile:"";
        }
        return $res;
    }


    /***
     * @param $params
     * @return bool
     * 添加医师信息
     */
    public function addDoctor($params)
    {
        $tool = new Tool();
        if (isset($params['id']) && !empty($params['id'])) {
            if (isset($params['account'])) {
                $account = $this->where([['account', '=', $params['account']], ['id', '!=', $params['id']]])->first();
                if ($account) {
                    return "该账号已经存在,不能重复添加";
                }
            }
            $doctorInfo = self::getInfoById($params['id']);
            $doctorInfo->real_name = isset($params['real_name']) && !empty($params['real_name']) ? $params['real_name'] : $doctorInfo->real_name;
            $doctorInfo->idcard = isset($params['idcard']) && !empty($params['idcard']) ? $params['idcard'] : $doctorInfo->idcard;
            $doctorInfo->clinic_id = isset($params['clinic_id']) && !empty($params['clinic_id']) ? $params['clinic_id'] : $doctorInfo->clinic_id;
            $doctorInfo->hospital = isset($params['hospital']) && !empty($params['hospital']) ? $params['hospital'] : $doctorInfo->hospital;
            $doctorInfo->front_card = isset($params['front_card']) && !empty($params['front_card']) ? $params['front_card'] : $doctorInfo->front_card;
            $doctorInfo->behind_card = isset($params['behind_card']) && !empty($params['behind_card']) ? $params['behind_card'] : $doctorInfo->behind_card;
            $doctorInfo->profile = isset($params['profile']) && !empty($params['profile']) ? $params['profile'] : $doctorInfo->profile;
            $doctorInfo->certificate = isset($params['certificate']) && !empty($params['certificate']) ? $tool::handelString($params['certificate']) : $doctorInfo->certificate;
            $doctorInfo->introduce = isset($params['introduce']) && !empty($params['introduce'])  ? $params['introduce'] : $doctorInfo->introduce;
            $doctorInfo->skill = isset($params['skill']) && !empty($params['skill']) ? $params['skill'] : $doctorInfo->skill;
//            $doctorInfo->phone = isset($params['phone']) ? $params['phone'] : $doctorInfo->phone;
            $doctorInfo->password = isset($params['password'])&& !empty($params['password']) ? bcrypt($params['password']) : $doctorInfo->password;
//            $doctorInfo->account = isset($params['phone'])  ? $params['phone'] : $doctorInfo->phone;
//            $doctorInfo->work_id = isset($params['work_id'])  ? $params['work_id'] : $doctorInfo->work_id;
            $doctorInfo->age = isset($params['age']) && !empty($params['age']) ?$params['age']:$doctorInfo->age;
            $doctorInfo->sex = isset($params['sex']) && !empty($params['sex']) ?$params['sex']:$doctorInfo->sex;
            $doctorInfo->state = 0;
            $doctorInfo->alipay_account = isset($params['alipay_account']) && !empty($params['alipay_account']) ?$params['alipay_account']:$doctorInfo->alipay_account;
            $doctorInfo->alipay_name = isset($params['alipay_name']) && !empty($params['alipay_name']) ?$params['alipay_name']:$doctorInfo->alipay_name;
            $doctorInfo->professional_id = isset($params['professional_id']) && !empty($params['professional_id']) ? $params['professional_id'] : $doctorInfo->professional_id;
            $td = $doctorInfo->save();
            //更新环信
            if (isset($params['real_name']) || isset($params['profile'])) { //修改环信
                $ease = new Easemob();
                $dd['image'] = isset($params['profile']) ? $params['profile']:$doctorInfo->profile;
                $dd['name'] = isset($params['real_name']) ? $params['real_name']:$doctorInfo->real_name;
                $dd['im_id'] = 'doctor' . config("omnipay.Im.salt") . $params['id'];
                $ease::updateUserInfo($dd);
            }
            Tool::SetDoctorAndUpToken($params['api_token'],$doctorInfo->account);
        } else {
            $account = $this->where([['account', '=', $params['account']]])->first();
            if ($account) {
                return "该账号已经存在,不能重复添加";
            }
            $this->real_name = $params['real_name'];
            $this->idcard = $params['idcard'];
            $this->clinic_id = $params['clinic_id'];
            $this->hospital = $params['hospital'];
            $this->front_card = $params['front_card'];
            $this->behind_card = $params['behind_card'];
            $this->profile = $params['profile'];
            if (isset($params['certificate'])) {
                $this->certificate = $tool::handelString($params['certificate']);
            }
            $this->introduce = $params['introduce'];
            $this->skill = $params['skill'];
            $this->phone = $params['phone'];
            $this->password = bcrypt($params['password']);
            $this->account = $params['phone'];
            $this->work_id = $params['work_id'];
            $this->age = isset($params['age'])?$params['age']:"";
            $this->sex = isset($params['sex'])?$params['sex']:1;
            $this->professional_id = $params['professional_id'];
            $this->is_admin = 0;
            $adm = $this->where([['work_id','=',$params['work_id']],['is_admin','=',1]])->first();
            $this->service_type = $adm->service_type;
            $this->imagetext_price = $adm->imagetext_price;
            $this->phone_price = $adm->phone_price;
            $this->platform_rate = $adm->platform_rate;
            $this->imagetext_time = $adm->imagetext_time;
            $this->phone_time = $adm->phone_time;
            $this->consult_type = $adm->consult_type;
            $td = $this->save();
            //更新环信
            if (isset($params['real_name']) || $params['profile']) { //修改环信
                $ease = new Easemob();
                $dd['image'] = $params['profile'];
                $dd['name'] = $params['real_name'];
                $dd['im_id'] =   'doctor' . config("omnipay.Im.salt") . $this->id;
                $ease::updateUserInfo($dd);
            }
        }
        if ($td) {
            return true;
        }
        return false;
    }

    /***
     * @param $filter
     * @return mixed
     * 获取工作室管理员
     */
    public function getResponsiblePerson($filter)
    {
        $tool = new Tool();
        $host = new Url();
        $res = $this->with(['clinic', 'professional'])->where([['work_id', '=', $filter['work_id']], ['is_admin', '=', 1]])->first();
        $res->profile = $host::getHttpHost() . 'upload/' . $res->profile;
        $res->front_card = $host::getHttpHost() . 'upload/' . $res->front_card;
        $res->behind_card = $host::getHttpHost() . 'upload/' . $res->behind_card;
        $res->certificate = $tool->addHostToImage(json_decode($res->certificate, true));
        return $res;
    }

    /***
     * @param $filter
     * @return bool|string
     * 修改密码
     */
    public function updatePassword($filter)
    {
        $info = self::getInfoById($filter['id']);
        if ($info->password == bcrypt($filter['password'])) {
            return "修改密码与原密码不能相同";
        }
        $info->password == bcrypt($filter['password']);
        $res = $info->save();
        if ($res) {
            return true;
        }
        return "修改失败";
    }

    /**
     * @param $filter
     * @return bool|string
     * 删除医师
     */
    public function deleteDoctor($filter)
    {
        $info = self::getInfoById($filter['id']);
        if (!$info) {
            return "该用户不存在,不能删除!";
        }
        if ($info->is_admin == 1) {
            return "该医生为工作室管理员,不能删除!";
        }
        $res = (new OrderGoods())
            ->from("c_order_goods as order_goods")
            ->join("c_orders as order",'order.id','=','order_goods.order_id')
            ->where([['order_goods.goods_id','=',$filter['id']],['order.pay_status','=',1],['order.order_status','=',1]])
            ->whereIn("order.order_type",[3,4])
            ->first();
        if(!empty($res)){
            return "该医生已有咨询记录,不能删除!";
        }
        $da = $this::destroy($filter['id']);
        if ($da) {
            return true;
        }
        return "删除失败!";
    }

    /**
     * @param $token
     * @return mixed
     * 退出
     */
    public function loginOut($token)
    {
        return $this->where([['api_token', '=', $token]])->update(['online' => 0]);
    }

}
